import { Pool } from "pg";
import { DB_USER, DB_PASSWORD, DB_HOST, DB_POST, DB_DATABASE } from '$lib/config/variable';

const pool = new Pool({
  host: DB_HOST,
  port: DB_POST,
  user: DB_USER,
  password: DB_PASSWORD,
  database: DB_DATABASE,
  max: 10,
  min: 2,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000
});

export async function query(sql, params = []) {
  const client = await pool.connect();
  try {
    const result = await client.query(sql, params);
    return result.rows;
  } catch (err) {
    console.error("❌ SQL Error:", err.message);
    throw err;
  } finally {
    client.release();
  }
}

export async function transaction(callback) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await callback(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("❌ Transaction Error:", err.message);
    throw err;
  } finally {
    client.release();
  }
}
